Managing Roles
Roles
in ASP.NET simplify the implementation of applications that require
authorization. A role is just a logical attribute assigned to a user.
An ASP.NET role is a plain string that refers to the logical role the
user plays in the context of the application. In terms of
configuration, each user can be assigned one or more roles. This
information is attached to the identity object, and the application
code can check it before the execution of critical operations.
For
example, an application might define two roles—Admin and Guest, each
representative of a set of application-specific permissions. Users
belonging to the Admin role can perform tasks that other users are
prohibited from performing.
Note
Assigning
roles to a user account doesn’t add any security restrictions by
itself. It is the responsibility of the application to ensure that
authorized users perform critical operations only if they are members
of a certain role. |
In
ASP.NET, the role manager feature simply maintains the relationship
between users and roles. ASP.NET 1.1 has no built-in support for
managing roles. You can attach some role information to an identity,
but this involves writing some custom code. Checking roles is easier,
but ASP.NET 2.0 makes the whole thing significantly simpler.
Note
The
Role Management API, although it consists of different methods and
properties, works like the Membership API from a mechanical standpoint.
Many of the concepts you read in the previous section also apply to
role management. |
The Role Management API
The
role management API lets you define roles as well as specify
programmatically which users are in which roles. The easiest way to
configure role management, define roles, add users to roles, and create
access rules is to use WSAT. (See Figure 17-11.) You enable role management by adding the following script to your application’s web.config file:
<roleManager enabled="true" />
You can use roles to establish access rules for pages and folders. The following <authorization> block states that only Admin members can access all the pages controlled by the web.config file:
<configuration>
<system.web>
<authorization>
<allow roles="Admin" />
<deny users="*" />
</authorization>
</system.web>
<configuration>
The order in which you place <allow> and <deny>tags is important. Permissions and denies are processed in the order in which they appear in the configuration file.
WSAT
provides a visual interface for creating associations between users and
roles. If necessary, you can instead perform this task programmatically
by calling various role manager methods. The following code snippet
demonstrates how to create the Admin and Guest roles and populate them
with usernames:
Roles.CreateRole("Admin");
Roles.AddUsersToRole("DinoE", "Admin");
Roles.CreateRole("Guest");
string[] guests = new string[2];
guests[0] = "JoeUsers";
guests[1] = "Godzilla";
Roles.AddUsersToRole(guests, "Guest")
At run time, information about the logged-in user is available through the HTTP context User
object. The following code demonstrates how to determine whether the
current user is in a certain role and subsequently enable specific
functions:
if (User.IsInRole("Admin"))
{
// Enable functions specific to the role
...
}
When role management is enabled, ASP.NET 2.0 looks up the roles for the current user and binds that information to the User object. This same feature had to be manually coded in ASP.NET 1.x.
Note
In ASP.NET 1.x, you typically cache role information on a per-user basis through a cookie or for all users in a custom Cache entry. In both cases, you do this when the application starts by handling the Application_Start event in the global.asax file. After that, you write a get function to read role information from the store and call it wherever required. |
The Roles Class
When role management is enabled, ASP.NET creates an instance of the Roles class and adds it to the current request context—the HttpContext object.
Table 4. Methods of the Roles Class
Method | Description |
---|
AddUsersToRole | Adds an array of users to a role. |
AddUsersToRoles | Adds an array of users to multiple roles. |
AddUserToRole | Adds a user to a role. |
AddUserToRoles | Adds a user to multiple roles. |
CreateRole | Creates a new role. |
DeleteCookie | Deletes the cookie that the role manager used to cache all the role data. |
DeleteRole | Deletes an existing role. |
FindUsersInRole | Retrieves
all the user names in the specified role that match the provider user
name string. The user names found are returned as a string array. |
GetAllRoles | Returns all the available roles. |
GetRolesForUser | Returns a string array listing the roles that a particular member belongs to. |
GetUsersInRole | Returns a string array listing the users that belong to a particular role. |
IsUserInRole | Determines whether the specified user is in a particular role. |
RemoveUserFromRole | Removes a user from a role. |
RemoveUserFromRoles | Removes a user from multiple roles. |
RemoveUsersFromRole | Removes multiple users from a role. |
RemoveUsersFromRoles | Removes multiple users from multiple roles. |
RoleExists | Returns true if the specified role exists. |
Table 5 lists the properties available in the Roles class. All the properties are static and read-only. They owe their value to the settings in the <roleManager> configuration section.
Table 5. Properties of the Roles Class
Property | Description |
---|
ApplicationName | Returns the provider’s nickname. |
CacheRolesInCookie | Returns true if cookie storage for role data is enabled. |
CookieName | Specifies the name of the cookie used by the role manager to store the roles. Defaults to .ASPXROLES. |
CookiePath | Specifies the cookie path. |
CookieProtectionValue | Specifies an option for securing the roles cookie. Possible values are All, Clear, Hashed, and Encrypted. |
CookieRequireSSL | Indicates whether the cookie requires SSL. |
CookieSlidingExpiration | Indicates whether the cookie has a fixed expiration time or a sliding expiration. |
CookieTimeout | Returns the time, in minutes, after which the cookie will expire. |
CreatePersistentCookie | Creates a role cookie that survives the current session. |
Domain | Indicates the domain of the role cookie. |
Enabled | Indicates whether role management is enabled. |
MaxCachedResults | Indicates the maximum number of roles that can be stored in a cookie for a user. |
Provider | Returns the current role provider. |
Providers | Returns a list of all supported role providers. |
Some methods in the Roles
class need to query continuously for the roles associated with a given
user, so when possible, the roles for a given user are stored in an
encrypted cookie. On each request, ASP.NET checks to see whether the
cookie is present; if so, it decrypts the role ticket and attaches any
role information to the User object. By default, the cookie is a session cookie and expires as soon as the user closes the browser.
Note
that the cookie is valid only if the request is for the current user.
When you request role information for other users, the information is
read from the data store using the configured role provider.
Note
Role
management passes through the role manager HTTP module. The module is
responsible for adding the appropriate roles to the current identity
object, such as the User object. The module listens for the AuthenticateRequest event and does its job. This is exactly the kind of work you need to code for yourself in ASP.NET 1.x. |
The Role Provider
For
its I/O activity, the role manager uses the provider model and a
provider component. The role provider is a class that inherits the RoleProvider class. The schema of a role provider is not much different from that of a membership provider. Table 6 details the members of the RoleProvider class.
Table 6. Methods of the RoleProvider Class
Method | Description |
---|
AddUsersToRoles | Adds an array of users to multiple roles. |
CreateRole | Creates a new role. |
DeleteRole | Deletes the specified role. |
FindUsersInRole | Returns the name of users in a role matching a given user name pattern. |
GetAllRoles | Returns the list of all available roles. |
GetRolesForUser | Gets all the roles a user belongs to. |
GetUsersInRole | Gets all the users who participate in the given role. |
IsUserInRole | Indicates whether the user belongs to the role. |
RemoveUsersFromRoles | Removes an array of users from multiple roles. |
RoleExists | Indicates whether a given role exists. |
You can see the similarity between some of these methods and the programming interface of the Roles class. As we’ve seen for membership, this is not just coincidental.
ASP.NET ships with a few built-in role providers—SqlRoleProvider (default), WindowsTokenRoleProvider, and AuthorizationStoreRoleProvider. The SqlStoreProvider class stores role information in the same MDF file in SQL Server 2005 Express as the default membership provider. For WindowsTokenRoleProvider,
role information is obtained based on the settings defined for the
Windows domain (or Active Directory) the user is authenticating
against. This provider does not allow for adding or removing roles. The
AuthorizationStoreRoleProvider
class manages storage of role information for an authorization manager
(AzMan) policy store. Supported on Windows Server 2003, Windows XP
Professional, and Windows 2000 Server, AzMan is a separate Windows
download that enables you to group individual operations together to
form tasks. You can then authorize roles to perform specific tasks,
individual operations, or both. AzMan provides an MMC snap-in to manage
roles, tasks, operations, and users. Role information is stored in a
proper policy store, which can be an XML file, an Active Directory, or
an ADAM server.
Custom role providers can be created deriving from RoleProvider and registered using the child <providers> section in the <roleManager>
section. Note that the process for doing so is nearly identical to the
process you saw for the custom membership provider we explored
previously.